﻿using System.Collections.Concurrent;

namespace Basmus.Values
{
    public class CachedBuilder<T> : IBuilder<T>
    {
        private readonly ConcurrentDictionary<ValuesContext, T> _cache = new ConcurrentDictionary<ValuesContext, T>();

        private readonly IBuilder<T> _builder;

        public CachedBuilder(IBuilder<T> builder)
        {
            _builder = builder;
        }

        public T Build(ValuesContext valuesContext)
        {
            var target = _cache.GetOrAdd(valuesContext, context => _builder.Build(valuesContext));
            return target;
        }
    }
}